Switching Between Windows in Selenium WebDriver
Switching Between Windows in Selenium WebDriver is the process of changing the current browser context from one browser window or tab to another during test execution. Modern web applications frequently open links, authentication pages, reports, payment pages, documentation, or external services in a new tab or window.
Selenium WebDriver identifies each open browser window or tab using a unique Window Handle. To work with another window, we first capture the available window handles and then use driver.switchTo().window() to move the WebDriver focus to the required window.
In Selenium, tabs and windows are handled through the same window-handle mechanism. Selenium's official documentation describes getWindowHandle() as the handle of the current window and getWindowHandles() as the set of handles for all open windows in the current WebDriver session. :contentReference[oaicite:0]{index=0}
Selenium Training: Selenium Training Course
Register for Course Demo: Register for Selenium Course Demo
1. What is Switching Between Windows?
Switching between windows means moving Selenium's control from the currently active browser context to another open browser tab or window.
For example, suppose an application has a login page and clicking a link opens a documentation page in a new tab:
Main Window
|
| Click "Documentation"
v
New Tab / Window
|
| Selenium switches control
v
Validate Documentation Page
|
| Switch back
v
Main Window
Selenium does not automatically allow subsequent commands to target every newly opened window. The test must explicitly switch to the required window handle before interacting with elements in that context. :contentReference[oaicite:1]{index=1}
2. Why Window Switching is Required
When a web application opens a new tab or window, Selenium needs to know which browsing context should receive the next command.
- The original page remains open.
- A new tab or window may be created.
- Selenium assigns a unique handle to each window.
- The test captures the handles.
- The test switches to the required handle.
- Actions can then be performed in that window.
- The test can switch back to the original window when required.
3. Window Handle
A window handle is a unique identifier associated with a browser window or tab within a WebDriver session.
In Java Selenium, the current window handle is represented by a String.
String parentWindow = driver.getWindowHandle();
The value is generated and managed by the WebDriver session. Test scripts should store handles rather than attempting to construct them manually.
4. getWindowHandle()
The getWindowHandle() method returns the handle of the current browser window.
String currentWindow = driver.getWindowHandle();
System.out.println("Current Window: " + currentWindow);
Selenium's Java API specifies that this method returns the current window handle, which can later be used to switch back to that window. :contentReference[oaicite:2]{index=2}
5. getWindowHandles()
The getWindowHandles() method returns a Set<String> containing the handles of all open browser windows or tabs belonging to the current WebDriver session.
Set<String> allWindows = driver.getWindowHandles();
for (String window : allWindows) {
System.out.println(window);
}
Selenium's Java API defines this as a set of window handles that can be passed to switchTo() to change the current browsing context. :contentReference[oaicite:3]{index=3}
6. switchTo().window()
The switchTo().window() method changes WebDriver's current browsing context to the specified window handle.
driver.switchTo().window(windowHandle);
After switching, commands such as findElement(), getTitle(), getCurrentUrl(), and other WebDriver operations are performed against the selected window.
7. Basic Window Switching Flow
Start Test
|
v
Open Parent Window
|
v
Store Parent Handle
|
v
Click Link / Button
|
v
New Window or Tab Opens
|
v
Get All Window Handles
|
v
Identify Target Window
|
v
Switch to Target Window
|
v
Perform Actions / Assertions
|
v
Close Target Window if Required
|
v
Switch Back to Parent
|
v
Continue Test
|
v
Quit Browser
8. Basic Example of Switching Between Two Windows
String parentWindow = driver.getWindowHandle();
driver.findElement(By.linkText("Open New Window")).click();
Set<String> allWindows = driver.getWindowHandles();
for (String window : allWindows) {
if (!window.equals(parentWindow)) {
driver.switchTo().window(window);
break;
}
}
System.out.println(driver.getTitle());
9. Complete Java Example
import java.time.Duration;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
public class WindowSwitchExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.manage().window().maximize();
driver.get("https://example.com");
String parentWindow = driver.getWindowHandle();
driver.findElement(By.linkText("Open New Window")).click();
WebDriverWait wait = new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
wait.until(d -> d.getWindowHandles().size() > 1);
Set<String> allWindows = driver.getWindowHandles();
for (String window : allWindows) {
if (!window.equals(parentWindow)) {
driver.switchTo().window(window);
System.out.println(
"New Window Title: " + driver.getTitle()
);
break;
}
}
driver.switchTo().window(parentWindow);
System.out.println(
"Parent Window Title: " + driver.getTitle()
);
} finally {
driver.quit();
}
}
}
10. Step-by-Step Window Switching Process
Step 1: Open the Parent Window
driver.get("https://example.com");
Step 2: Store the Parent Handle
String parentWindow = driver.getWindowHandle();
Step 3: Perform the Action that Opens Another Window
driver.findElement(By.linkText("Open New Window")).click();
Step 4: Wait for the New Window
wait.until(d -> d.getWindowHandles().size() > 1);
Step 5: Get All Handles
Set<String> windows = driver.getWindowHandles();
Step 6: Find the Target Window
for (String window : windows) {
if (!window.equals(parentWindow)) {
driver.switchTo().window(window);
break;
}
}
Step 7: Perform Actions
System.out.println(driver.getTitle());
System.out.println(driver.getCurrentUrl());
Step 8: Switch Back
driver.switchTo().window(parentWindow);
11. Parent Window and Child Window
The window from which the test starts is commonly called the parent window. A newly opened tab or window is commonly referred to as the child window.
Parent Window
|
| Click
v
Child Window
|
| Test actions
v
Switch Back
|
v
Parent Window
The terms parent and child are convenient for describing test flow. Technically, Selenium works with top-level browsing contexts identified by window handles.
12. Storing the Parent Window
Always store the original handle before opening another window when the test needs to return to the original page.
String parentWindow = driver.getWindowHandle();
This makes the test independent of assumptions about the numerical position of the parent window.
13. Finding the New Window
A common approach is to compare every current handle with the original handle.
for (String window : driver.getWindowHandles()) {
if (!window.equals(parentWindow)) {
driver.switchTo().window(window);
break;
}
}
This approach is useful when exactly one additional window is expected.
14. Why You Should Not Depend on Window Index
A beginner-friendly example often converts the set to an array and accesses index 1.
Object[] windows = driver.getWindowHandles().toArray();
driver.switchTo().window((String) windows[1]);
Although this can work for a simple two-window demonstration, robust tests should not generally depend on a particular handle position. A better strategy is to compare handles or identify the target window using a property such as its title, URL, or a unique element.
15. Switching Based on Window Title
When several windows are open, you can switch through the available handles and inspect the title.
for (String window : driver.getWindowHandles()) {
driver.switchTo().window(window);
if (driver.getTitle().equals("Selenium Documentation")) {
break;
}
}
This is useful when the target window has a predictable and unique title.
16. Switching Based on URL
Another approach is to identify the target window using its current URL.
for (String window : driver.getWindowHandles()) {
driver.switchTo().window(window);
if (driver.getCurrentUrl().contains("/documentation")) {
break;
}
}
URL matching can be useful when different windows have similar or recognizable URL patterns.
17. Switching Based on a Unique Element
If the title or URL is not reliable, a unique element can be used to identify the required page.
for (String window : driver.getWindowHandles()) {
driver.switchTo().window(window);
if (!driver.findElements(By.id("documentationHeading")).isEmpty()) {
break;
}
}
This technique is useful when the target page contains a distinctive element that does not exist on the other pages.
18. Waiting for a New Window
A new browser context may not appear immediately after clicking a link. Therefore, synchronization is important.
WebDriverWait wait = new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
wait.until(d -> d.getWindowHandles().size() > 1);
Waiting for the expected number of windows is preferable to adding an arbitrary fixed delay.
19. Why Thread.sleep() Should Be Avoided
A common beginner approach is:
Thread.sleep(5000);
This pauses execution for a fixed amount of time regardless of whether the new window has already appeared.
A condition-based wait is generally more appropriate:
wait.until(d -> d.getWindowHandles().size() > 1);
- It waits for a condition.
- It can continue as soon as the condition is satisfied.
- It avoids unnecessary fixed delays.
- It makes synchronization clearer.
20. Switching Back to the Parent Window
After completing actions in the child window, use the stored parent handle to return.
driver.switchTo().window(parentWindow);
This is one of the most important steps when a test continues interacting with the original page.
21. Closing the Child Window
When the test is finished with the child window, it can be closed using driver.close().
driver.close();
The Selenium Java API specifies that close() closes the current window; if it is the last open window, the browser session is also ended. :contentReference[oaicite:4]{index=4}
22. Close and Switch Back
After closing the child window, switch back to a valid remaining window.
driver.close();
driver.switchTo().window(parentWindow);
Selenium's documentation specifically notes that after closing a window, the driver should be switched back to another valid window handle before continuing. Otherwise, a NoSuchWindowException can occur. :contentReference[oaicite:5]{index=5}
23. close() vs quit()
| Method | Purpose | Effect |
| close() | Closes current window/tab | Only current browsing context is closed |
| quit() | Ends WebDriver session | Closes all associated windows and ends the session |
Use close() when you intentionally want to close the current window while continuing with another open window. Use quit() at the end of the test to terminate the browser session. :contentReference[oaicite:6]{index=6}
24. Complete Example with Close and Return
String parentWindow = driver.getWindowHandle();
driver.findElement(By.linkText("Open New Window")).click();
WebDriverWait wait = new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
wait.until(d -> d.getWindowHandles().size() == 2);
for (String window : driver.getWindowHandles()) {
if (!window.equals(parentWindow)) {
driver.switchTo().window(window);
break;
}
}
System.out.println(driver.getTitle());
driver.close();
driver.switchTo().window(parentWindow);
System.out.println(driver.getTitle());
25. Switching Between Three Windows
Window switching is not limited to two windows. A test may have several tabs or windows open.
String parent = driver.getWindowHandle();
driver.findElement(By.id("window1")).click();
driver.findElement(By.id("window2")).click();
Set<String> windows = driver.getWindowHandles();
System.out.println("Total Windows: " + windows.size());
for (String window : windows) {
driver.switchTo().window(window);
System.out.println("Title: " + driver.getTitle());
}
26. Three-Window Flow
Window A
|
+----> Window B
|
+----> Window C
Test can switch:
A -> B
B -> C
C -> A
A -> C
B -> A
27. Switching from One Child to Another Child
If multiple child windows exist, store or identify their handles and switch directly.
driver.switchTo().window(windowA);
driver.switchTo().window(windowB);
driver.switchTo().window(parentWindow);
Each call changes the current WebDriver browsing context.
28. Using a Map for Named Window Handles
For complex automation frameworks, window handles can be stored with meaningful names.
Map<String, String> windows = new HashMap<>();
windows.put("parent", parentWindow);
windows.put("report", reportWindow);
windows.put("documentation", documentationWindow);
This makes the test code easier to understand than repeatedly working with anonymous handle variables.
29. Utility Method for Switching
A reusable utility method can reduce duplicate window-switching code.
public static void switchToWindow(
WebDriver driver,
String targetTitle) {
for (String window : driver.getWindowHandles()) {
driver.switchTo().window(window);
if (driver.getTitle().equals(targetTitle)) {
return;
}
}
throw new RuntimeException(
"Target window not found: " + targetTitle
);
}
Usage:
switchToWindow(
driver,
"Selenium Documentation"
);
30. Utility Method to Return to Parent
public static void switchToParent(
WebDriver driver,
String parentHandle) {
driver.switchTo().window(parentHandle);
}
31. Selenium 4: Creating a New Tab
Selenium 4 provides an API for creating a new top-level browsing context and switching to it immediately.
driver.switchTo().newWindow(WindowType.TAB);
The Selenium documentation describes this operation as creating a new tab or window and focusing the new browsing context. :contentReference[oaicite:7]{index=7}
32. Selenium 4: Creating a New Window
driver.switchTo().newWindow(WindowType.WINDOW);
Required import:
import org.openqa.selenium.WindowType;
Unlike a link that opens a new context, this command explicitly asks Selenium to create a new tab or window and switch to it.
33. New Tab Example
driver.get("https://example.com");
String parentWindow = driver.getWindowHandle();
driver.switchTo().newWindow(WindowType.TAB);
driver.get("https://www.selenium.dev/");
System.out.println(driver.getTitle());
driver.switchTo().window(parentWindow);
System.out.println("Returned to parent");
34. New Window Example
driver.get("https://example.com");
String parentWindow = driver.getWindowHandle();
driver.switchTo().newWindow(WindowType.WINDOW);
driver.get("https://www.selenium.dev/");
System.out.println(driver.getCurrentUrl());
driver.switchTo().window(parentWindow);
35. Tabs vs Windows
From the WebDriver perspective, Selenium handles browser tabs and windows using window handles. The distinction is primarily how the browser presents the top-level browsing context to the user. :contentReference[oaicite:8]{index=8}
| Feature | Tab | Window |
| Window Handle | Yes | Yes |
| switchTo().window() | Yes | Yes |
| getWindowHandles() | Included | Included |
| Can be closed with close() | Yes | Yes |
| Selenium 4 new context | WindowType.TAB | WindowType.WINDOW |
36. Window Switching vs Frame Switching
Window switching and frame switching are different operations.
| Window Switching | Frame Switching |
| Moves between tabs/windows | Moves into an iframe |
| Uses window handles | Uses frame reference, name, index, or WebElement |
| Uses switchTo().window() | Uses switchTo().frame() |
| Top-level browsing context | Nested browsing context |
37. Window Switching vs Alert Switching
| Window | Alert |
| Uses window handle | Uses alert object |
| driver.switchTo().window(handle) | driver.switchTo().alert() |
| Represents browser tab/window | Represents JavaScript dialog |
38. Common Exception: NoSuchWindowException
NoSuchWindowException can occur when Selenium attempts to interact with a window that no longer exists or when the driver remains focused on a window that was already closed.
driver.close();
// Incorrect if current context is now closed
driver.findElement(By.id("username")).sendKeys("admin");
Correct approach:
driver.close();
driver.switchTo().window(parentWindow);
driver.findElement(By.id("username"))
.sendKeys("admin");
39. Common Exception: TimeoutException
If the expected new window does not appear within the configured wait period, a timeout may occur.
wait.until(d -> d.getWindowHandles().size() > 1);
Possible causes include:
- The click did not work.
- The target link was incorrect.
- The application did not open a new context.
- The application was slow.
- The expected window count was incorrect.
40. Common Exception: NoSuchElementException
After switching to a window, the test may still search for an element that belongs to another page.
driver.switchTo().window(childWindow);
driver.findElement(By.id("parentPageElement")).click();
The locator may be correct but the element may not exist in the current browsing context. Verify the title, URL, and page content after switching.
41. Verify the Window After Switching
After switching, it is good practice to verify that the driver is actually in the expected context.
driver.switchTo().window(childWindow);
System.out.println("Handle: " + driver.getWindowHandle());
System.out.println("Title: " + driver.getTitle());
System.out.println("URL: " + driver.getCurrentUrl());
42. Assertion After Window Switching
In TestNG, assertions can verify that the expected page opened.
Assert.assertEquals(
driver.getTitle(),
"Selenium Documentation"
);
Required import:
import org.testng.Assert;
43. TestNG Example
import java.time.Duration;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.Test;
public class WindowTest {
@Test
public void switchBetweenWindows() {
WebDriver driver = new ChromeDriver();
try {
driver.manage().window().maximize();
driver.get("https://example.com");
String parentWindow = driver.getWindowHandle();
driver.findElement(
By.linkText("Open New Window")
).click();
WebDriverWait wait = new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
wait.until(d -> d.getWindowHandles().size() == 2);
Set<String> windows = driver.getWindowHandles();
for (String window : windows) {
if (!window.equals(parentWindow)) {
driver.switchTo().window(window);
Assert.assertNotNull(
driver.getTitle()
);
break;
}
}
driver.switchTo().window(parentWindow);
} finally {
driver.quit();
}
}
}
44. Real-World Example: Product Details
Consider an e-commerce website where clicking a product comparison link opens product information in a new tab.
Parent Product Page
|
| Click Compare
v
Product Details Tab
|
| Validate price/details
v
Close Tab
|
v
Return to Product Page
The automation can store the product page handle, switch to the new tab, validate the required information, close the tab, and return to the parent.
45. Real-World Example: Documentation Link
A web application may open external documentation in a new tab.
String parent = driver.getWindowHandle();
driver.findElement(By.linkText("Documentation")).click();
WebDriverWait wait = new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
wait.until(d -> d.getWindowHandles().size() > 1);
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(parent)) {
driver.switchTo().window(handle);
break;
}
}
Assert.assertTrue(
driver.getTitle().contains("Documentation")
);
driver.close();
driver.switchTo().window(parent);
46. Real-World Example: Reports
Testing applications often open generated reports in a separate tab.
Login Page
|
v
Dashboard
|
v
Generate Report
|
v
Report Tab
|
v
Validate Report
|
v
Close Report
|
v
Dashboard
47. Real-World Example: Authentication Flow
Some applications may open an authentication or identity-provider page in another tab or window. The automation should identify the new context, perform the required test actions, and return to the application context when appropriate.
The exact flow depends on the application's implementation and authentication architecture, so tests should identify the target context rather than assuming a fixed window position.
48. Handling Multiple Windows Using a Loop
Set<String> handles = driver.getWindowHandles();
for (String handle : handles) {
driver.switchTo().window(handle);
System.out.println(
"Window Title: " + driver.getTitle()
);
System.out.println(
"Window URL: " + driver.getCurrentUrl()
);
}
49. Finding a Window by Title
public static void switchToWindowByTitle(
WebDriver driver,
String expectedTitle) {
for (String handle : driver.getWindowHandles()) {
driver.switchTo().window(handle);
if (driver.getTitle().equals(expectedTitle)) {
return;
}
}
throw new RuntimeException(
"Window with title not found: " + expectedTitle
);
}
50. Finding a Window by URL
public static void switchToWindowByUrl(
WebDriver driver,
String expectedUrlPart) {
for (String handle : driver.getWindowHandles()) {
driver.switchTo().window(handle);
if (driver.getCurrentUrl().contains(expectedUrlPart)) {
return;
}
}
throw new RuntimeException(
"Window with URL pattern not found"
);
}
51. Page Object Model and Window Switching
In a Page Object Model framework, window-switching logic can be placed inside a utility or base class rather than duplicating it in every page class.
public class WindowUtils {
public static String getCurrentWindow(
WebDriver driver) {
return driver.getWindowHandle();
}
public static void switchToWindow(
WebDriver driver,
String handle) {
driver.switchTo().window(handle);
}
}
52. Window Switching Utility Class
import java.util.Set;
import org.openqa.selenium.WebDriver;
public class WindowUtils {
public static String getParentHandle(
WebDriver driver) {
return driver.getWindowHandle();
}
public static Set<String> getAllHandles(
WebDriver driver) {
return driver.getWindowHandles();
}
public static void switchToHandle(
WebDriver driver,
String handle) {
driver.switchTo().window(handle);
}
public static void switchToWindowByTitle(
WebDriver driver,
String title) {
for (String handle : driver.getWindowHandles()) {
driver.switchTo().window(handle);
if (driver.getTitle().equals(title)) {
return;
}
}
throw new RuntimeException(
"Window not found: " + title
);
}
}
53. Best Practice: Store the Original Handle
String parentWindow = driver.getWindowHandle();
Keeping the original handle makes returning to the starting page straightforward.
54. Best Practice: Wait for the Expected Window Count
wait.until(d -> d.getWindowHandles().size() == 2);
Do not immediately assume that the new context is already available.
55. Best Practice: Identify Windows Reliably
Prefer meaningful conditions such as:
- Window title
- Current URL
- Unique page element
- Difference between original and current handles
Avoid hard-coded assumptions such as always selecting index 1 when the test can identify the target more reliably.
56. Best Practice: Verify After Switching
driver.switchTo().window(targetWindow);
Assert.assertEquals(
driver.getTitle(),
"Expected Title"
);
Verification makes failures easier to diagnose.
57. Best Practice: Close Unused Windows
Leaving unnecessary windows open can make later test steps difficult to manage.
driver.close();
driver.switchTo().window(parentWindow);
58. Best Practice: Use quit() in Cleanup
At the end of the complete test or test suite, terminate the WebDriver session.
driver.quit();
This closes the associated browser contexts and ends the WebDriver session. :contentReference[oaicite:9]{index=9}
59. Common Mistakes in Window Switching
- Not storing the parent window handle.
- Trying to interact with a child page without switching to it.
- Using a fixed delay instead of a condition-based wait.
- Assuming window index 1 is always the required window.
- Closing a window and then continuing without switching to a valid handle.
- Confusing window switching with iframe switching.
- Forgetting to close unnecessary windows.
- Calling quit() too early.
- Using a title that is not unique to identify the target.
- Not validating the current URL or title after switching.
60. Incorrect vs Correct Approach
| Incorrect / Fragile Approach | Better Approach |
| Always use windows[1] | Identify the required handle |
| Use Thread.sleep() | Use explicit/condition-based waiting |
| Forget the parent handle | Store getWindowHandle() |
| Interact immediately after opening | Wait for the new context |
| Close child and continue | Close child and switch to parent |
| Assume title without validation | Verify title or URL |
61. Practical Mini Project: Documentation Window
Objective: Automate a scenario where clicking a documentation link opens a new window.
Test Steps
- Launch Chrome.
- Open the application.
- Store the current window handle.
- Click the documentation link.
- Wait until a second window appears.
- Collect all window handles.
- Identify the new window.
- Switch to the new window.
- Verify title or URL.
- Perform required validation.
- Close the documentation window.
- Switch back to the original application window.
- Continue the test.
- Quit WebDriver.
62. Practical Project Code
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
public class DocumentationWindowTest {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.manage().window().maximize();
driver.get("https://example.com");
String parentWindow =
driver.getWindowHandle();
driver.findElement(
By.linkText("Documentation")
).click();
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
wait.until(
d -> d.getWindowHandles().size() > 1
);
for (String handle :
driver.getWindowHandles()) {
if (!handle.equals(parentWindow)) {
driver.switchTo().window(handle);
Assert.assertTrue(
driver.getTitle()
.contains("Documentation")
);
driver.close();
break;
}
}
driver.switchTo().window(parentWindow);
System.out.println(
"Returned to application"
);
} finally {
driver.quit();
}
}
}
63. Debugging Window Switching
When a window-switching test fails, print all available handles, titles, and URLs.
for (String handle : driver.getWindowHandles()) {
driver.switchTo().window(handle);
System.out.println(
"Handle: " + handle
);
System.out.println(
"Title: " + driver.getTitle()
);
System.out.println(
"URL: " + driver.getCurrentUrl()
);
System.out.println("--------------------");
}
This is especially useful when several windows are open.
64. Window Switching Debug Flow
Test Fails
|
v
Print Window Count
|
v
Print All Handles
|
v
Print Titles
|
v
Print URLs
|
v
Identify Target Context
|
v
Verify Switch
|
v
Check Locator
|
v
Check Wait Condition
|
v
Run Test Again
65. Important Selenium Methods
| Method | Purpose |
| getWindowHandle() | Returns the current window handle |
| getWindowHandles() | Returns handles of all open windows/tabs |
| switchTo().window(handle) | Switches to a specified window |
| switchTo().newWindow(WindowType.TAB) | Creates and switches to a new tab |
| switchTo().newWindow(WindowType.WINDOW) | Creates and switches to a new window |
| close() | Closes the current window/tab |
| quit() | Closes all associated windows and ends the session |
66. Window Switching Cheat Sheet
// Current window
String parent = driver.getWindowHandle();
// All windows
Set<String> windows = driver.getWindowHandles();
// Switch
driver.switchTo().window(handle);
// Create new tab
driver.switchTo().newWindow(WindowType.TAB);
// Create new window
driver.switchTo().newWindow(WindowType.WINDOW);
// Close current
driver.close();
// Return to parent
driver.switchTo().window(parent);
// End session
driver.quit();
67. Interview Question: What is Window Switching?
Answer: Window switching is the process of changing WebDriver's current browsing context from one browser tab or window to another using window handles.
68. Interview Question: What is getWindowHandle()?
Answer: getWindowHandle() returns the unique handle of the current browser window or tab within the WebDriver session.
69. Interview Question: What is getWindowHandles()?
Answer: getWindowHandles() returns a set containing the handles of all currently available browser windows or tabs in the WebDriver session.
70. Interview Question: How do you switch to another window?
Answer: First obtain the target window handle and then use:
driver.switchTo().window(targetHandle);
71. Interview Question: How do you switch back to the parent window?
Answer: Store the parent handle before opening the child window and use that handle later.
String parent = driver.getWindowHandle();
driver.switchTo().window(parent);
72. Interview Question: Difference Between close() and quit()?
Answer: close() closes the current browser context, while quit() ends the WebDriver session and closes the associated browser windows.
73. Interview Question: How can you identify a specific window?
Answer: A window can be identified using its handle, title, URL, or a unique element on the target page. For reliable automation, use a property that uniquely identifies the intended context.
74. Interview Question: Why should Thread.sleep() be avoided?
Answer: Thread.sleep() uses a fixed delay. The test may wait longer than necessary or may continue too early if the required condition takes longer. Condition-based waits synchronize the test with the actual application state.
75. Interview Question: What happens if you close the current window and do not switch?
Answer: If the current browsing context has been closed, continuing to issue commands against it can result in NoSuchWindowException. The test should switch to another valid window handle after closing the current one. :contentReference[oaicite:10]{index=10}
76. Interview Question: Can Selenium switch between tabs?
Answer: Yes. Selenium handles browser tabs and windows through window handles. The same switchTo().window() mechanism can be used for either. :contentReference[oaicite:11]{index=11}
77. Interview Question: How do you create a new tab in Selenium 4?
Answer: Selenium 4 provides:
driver.switchTo().newWindow(WindowType.TAB);
78. Interview Question: How do you create a new browser window in Selenium 4?
Answer:
driver.switchTo().newWindow(WindowType.WINDOW);
79. Important Points to Remember
- Every top-level browser window/tab has a window handle.
- Use getWindowHandle() for the current context.
- Use getWindowHandles() for all open contexts.
- Use switchTo().window() to change the current context.
- Store the parent handle before opening a new context.
- Wait for the new window before switching.
- Do not blindly depend on a window index in robust tests.
- Use title, URL, or a unique element when necessary.
- After closing a child window, switch to a valid remaining window.
- Use quit() for final WebDriver cleanup.
80. Window Switching Checklist
- ☐ Open the application.
- ☐ Store the parent window handle.
- ☐ Perform the action that opens the new tab/window.
- ☐ Wait for the expected number of windows.
- ☐ Get all window handles.
- ☐ Identify the required handle.
- ☐ Switch to the target window.
- ☐ Verify title or URL.
- ☐ Perform required actions.
- ☐ Close the child window if required.
- ☐ Switch back to the parent window.
- ☐ Continue the test.
- ☐ Quit the WebDriver session during cleanup.
81. Best Practices Summary
| Practice | Recommendation |
| Parent Handle | Store it before opening another window |
| Synchronization | Wait for the expected window condition |
| Identification | Use handle, title, URL, or unique element |
| Window Index | Avoid depending on fixed indexes in robust tests |
| Closing | Close only the window that is no longer required |
| After Close | Switch to a valid remaining handle |
| Verification | Validate title, URL, or page element |
| Cleanup | Use quit() after the test/session |
| Framework | Move reusable switching logic into utilities |
82. Final Example
import java.time.Duration;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
public class CompleteWindowSwitching {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.manage().window().maximize();
driver.get("https://example.com");
String parentWindow =
driver.getWindowHandle();
driver.findElement(
By.linkText("Open New Window")
).click();
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
wait.until(
d -> d.getWindowHandles().size() > 1
);
Set<String> handles =
driver.getWindowHandles();
String childWindow = null;
for (String handle : handles) {
if (!handle.equals(parentWindow)) {
childWindow = handle;
break;
}
}
if (childWindow != null) {
driver.switchTo().window(childWindow);
System.out.println(
"Child Title: " +
driver.getTitle()
);
System.out.println(
"Child URL: " +
driver.getCurrentUrl()
);
driver.close();
}
driver.switchTo().window(parentWindow);
System.out.println(
"Parent Title: " +
driver.getTitle()
);
} finally {
driver.quit();
}
}
}
83. Quick Revision
1. Store parent handle:
String parent = driver.getWindowHandle();
2. Open another window/tab.
3. Wait for new window:
wait.until(d -> d.getWindowHandles().size() > 1);
4. Get all handles:
Set<String> handles = driver.getWindowHandles();
5. Find target handle.
6. Switch:
driver.switchTo().window(target);
7. Perform actions/assertions.
8. Close if required:
driver.close();
9. Switch back:
driver.switchTo().window(parent);
10. End session:
driver.quit();
84. Course Resources
To learn Selenium WebDriver, browser automation, window handling, locators, synchronization, Page Object Model, TestNG, automation frameworks, and practical testing, explore the Selenium training resources below.
85. Conclusion
Switching Between Windows is an important Selenium WebDriver skill for automating applications that use multiple browser tabs or windows. The core workflow is to store the current window handle, wait for a new context when necessary, obtain all available handles, identify the required window, switch using driver.switchTo().window(), perform the required actions, and finally return to a valid window or close the unused context.
For reliable automation, avoid unnecessary fixed delays and avoid blindly depending on window indexes. Instead, use explicit conditions and identify the target context through its handle, title, URL, or a unique page element. Selenium's official documentation provides the same fundamental window-handle and switching model for tabs and windows. :contentReference[oaicite:12]{index=12}
Recommended Selenium Course: Learn Selenium WebDriver with JustAcademy
Course Demo: Register for Course Demo